package com.dreamthen.exception;

import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.json.MappingJackson2JsonView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.BindException;

/**
 * @Author zengms
 * @Date 2023-11-14 20:09:16
 **/
@ControllerAdvice
public class GeneralExceptionHandler {

    @ExceptionHandler(Exception.class)
    public ModelAndView exception00(Exception ex, HandlerMethod handler,
                                    HttpServletRequest request, HttpServletResponse response) {
        System.out.println("******全局-exception******");
        ModelAndView modelAndView = null;
        //1、通过方法上的ResponseBody注解来判断是否返回json格式 或者 通过类上的RestController注解来判断是否返回json格式
        //2、通过请求头参数：Content-Type、Accept来判断返回是否json格式

        String contentType = request.getHeader("Content-Type");
        String accept = request.getHeader("Accept");

        /*
        if ((!StringUtils.isEmpty(contentType) && contentType.indexOf("application/json") >= 0)
                || (!StringUtils.isEmpty(accept) && accept.indexOf("application/json") >= 0)) {
            modelAndView = new ModelAndView(new MappingJackson2JsonView());
            modelAndView.addObject("code", 500);
            modelAndView.addObject("msg", ex.getMessage());
        }
        */

        RestController restController = null;
        ResponseBody annotation = null;
        if (handler instanceof HandlerMethod) {
            restController = handler.getBean().getClass().getAnnotation(RestController.class);
            annotation = handler.getMethod().getAnnotation(ResponseBody.class);
        }
        if (restController != null || annotation != null) {
            modelAndView = new ModelAndView(new MappingJackson2JsonView());
            modelAndView.addObject("code", 500);
            modelAndView.addObject("msg", ex.getMessage());
        } else {
            modelAndView = new ModelAndView();
            modelAndView.setViewName("error");
            modelAndView.addObject("ex", ex.getMessage());
        }

        return modelAndView;
    }
}
